// 引入外部资料库
import {
  getSetting,
  chooseAddress,
  openSetting,
  showModal,
  showToast,
} from "../../utils/asyncWx";
import regeneratorRuntime from "../../libs/runtime";

Page({
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0,
  },

  onShow: function (options) {
    const address = wx.getStorageSync("address");

    // 获取缓存中的购物车数据
    const cart = wx.getStorageSync("cart") || [];

    this.setCart(cart);

    this.setData({
      address,
    });
  },

  async handleChooseAddress() {
    // HACK before获取权限状态，并判断不同情况
    // wx.getSetting({
    //   success: (result) => {
    //     // TIPS 使用方括号获取属性值时需要添加引号
    //     const scopeAddress = result.authSetting["scope.address"];
    //     // 判断 scopeAddress 的值
    //     if (scopeAddress === true || scopeAddress === undefined) {
    //       wx.chooseAddress({
    //         success: (res) => {
    //           console.log(res);
    //         },
    //       });
    //     } else {
    //       wx.openSetting({
    //         success: (result) => {
    //           wx.chooseAddress({
    //             success: (gain) => {
    //               console.log(gain);
    //             },
    //           });
    //         },
    //       });
    //     }
    //   },
    // });

    try {
      /* HACK 基于 Promise 的版本(注意引入的 asyncWX.js 文件) */
      const getSettingResult = await getSetting();
      const scopeAddress = getSettingResult.authSetting["scope.address"];
      if (scopeAddress === false) {
        await openSetting();
      }
      const chooseAddressResult = await chooseAddress();
      // NOTE 将地址存入微信缓存中
      wx.setStorageSync("address", chooseAddressResult);
    } catch (err) {
      console.log(err);
    }
  },

  // 商品的选中状态
  handleItemChange(e) {
    const goods_id = e.currentTarget.dataset.id;
    let { cart } = this.data;
    let index = cart.findIndex((v) => v.goods_id === goods_id);
    cart[index].isChecked = !cart[index].isChecked;
    this.setCart(cart);
  },

  // 购物车状态变化的改变
  setCart(cart) {
    const allChecked = cart.length ? cart.every((v) => v.isChecked) : false;
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach((v) => {
      if (v.isChecked) {
        totalPrice += v.num * v.goods_price;
        totalNum += v.num;
      }
    });
    this.setData({
      cart,
      totalPrice,
      totalNum,
      allChecked,
    });
    wx.setStorageSync("cart", cart);
  },

  // 商品全选按钮的功能实现
  handleItemAllChecked() {
    let { cart, allChecked } = this.data;
    allChecked = !allChecked;
    cart.forEach((v) => (v.isChecked = allChecked));
    this.setCart(cart);
  },

  // 修改数据按钮功能
  async handleItemNum(e) {
    const { operation, id } = e.currentTarget.dataset;
    let { cart } = this.data;
    const index = cart.findIndex((v) => v.goods_id === id);
    if (cart[index].num === 1 && operation === -1) {
      const res = await showModal({ content: "确定删除此商品？" });
      if (res.confirm) {
        cart.splice(index, 1);
        this.setCart(cart);
      }
    } else {
      cart[index].num += operation;
      this.setCart(cart);
    }
  },

  // 结算功能
  async handlePay() {
    const { address, totalNum } = this.data;
    if (!address.userName) {
      await showToast({ title: "请选择收货地址" });
      return;
    }
    if (totalNum === 0) {
      await showToast({ title: "请选择商品" });
      return;
    }
    wx.navigateTo({
      url: "/pages/pay/pay",
    });
  },
});
